#!/bin/bash

# Define variables
NAMESPACE="k8s.io"
OUTPUT_DIR="/tmp/k8s_image_backups"
OUTPUT_FILE="k8s_images.tar.gz"
TEMP_DIR="$OUTPUT_DIR/images"

# Create a temporary directory for the images
echo "Creating temporary directory: $TEMP_DIR"
mkdir -p "$TEMP_DIR" || { echo "Failed to create directory. Exiting."; exit 1; }

# List all images and parse the output, skipping the header
echo "Exporting images from namespace '$NAMESPACE'..."
crictl images --digests | tail -n +2 | while read -r repo tag digest image_id size; do
    # Use the combination of repository and tag to get a unique image name
    IMAGE_IDENTIFIER="${repo}:${tag}"

    # Use ctr to export each image to the temporary directory.
    echo "Exporting image: $IMAGE_IDENTIFIER"
    # Use the image ID for the filename to ensure it is unique.
    sudo ctr -n "$NAMESPACE" image export "$TEMP_DIR/$image_id.tar" "$IMAGE_IDENTIFIER" || {
        echo "Failed to export image: $IMAGE_IDENTIFIER. Skipping."
    }
done

# Check if any images were exported
if [ -z "$(ls -A "$TEMP_DIR" 2>/dev/null)" ]; then
    echo "No images were successfully exported. Exiting."
    rm -r "$OUTPUT_DIR"
    exit 1
fi

# Create a single compressed tarball of all exported images
echo "Creating final compressed tarball: $OUTPUT_DIR/$OUTPUT_FILE"
tar -C "$TEMP_DIR" -czf "$OUTPUT_DIR/$OUTPUT_FILE" .

# Clean up temporary files
echo "Cleaning up temporary files..."
rm -r "$TEMP_DIR"

echo "Backup complete! Images are saved to $OUTPUT_DIR/$OUTPUT_FILE"